<template>
    <div class="min-h-screen bg-gray-50">
        <el-dialog v-model="dialogTableVisible" :title="title + '日历事件'" width="500">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="事件标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入事件标题" />
                </el-form-item>
                <el-form-item label="事件日期" prop="eventDate">
                    <el-date-picker v-model="form.eventDate" style="width: 100%;" type="date" placeholder="选择日期"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="事件类型" prop="eventType">
                    <el-select v-model="form.eventType" placeholder="请选择事件类型">
                        <el-option v-for="item in calendar_event_type" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="事件描述" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入事件描述" />
                </el-form-item>
                <el-form-item label="是否提醒" prop="isReminder">
                    <el-switch v-model="form.isReminder" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <div class="container mx-auto max-w-5xl p-6">
            <!-- 基本信息 -->
            <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden">
                <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
                    <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
                        <i class="fas fa-user text-blue-500"></i> 日历设置
                    </h2>
                </div>
                <div class="section-body p-6">
                    <el-calendar ref="calendar" v-model="calendarData">
                        <template #header="{ date }">
                            <el-button-group>
                                <el-button size="small" @click="selectDate('prev-month')">
                                    <el-icon>
                                        <ArrowLeft />
                                    </el-icon>
                                </el-button>
                                <el-button size="small"> <span>{{ date }}</span></el-button>
                                <el-button size="small" @click="selectDate('next-month')">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </el-button>
                            </el-button-group>
                            <el-button-group>
                                <el-button size="small" @click="selectDate('today')">今天</el-button>
                            </el-button-group>
                        </template>
                        <template #date-cell="{ data }">
                            <span style="font-size: 12px;" class="flex items-center justify-between">
                                <span> {{ dayjs(data.day).format('MM-DD') }}</span>
                                <el-icon @click.stop="calendarAddFun(data.day)">
                                    <Plus />
                                </el-icon>
                            </span>
                            <el-popover class="box-item" placement="bottom" :width="300">
                                <template #reference>
                                    <div v-if="getEventsByDate(data.day).length > 0" style="margin-top: 5px;">
                                        <el-tag v-for="event in getEventsByDate(data.day).slice(0, 4)"
                                            style="line-height: 20px;width: 100%;justify-content: flex-start;"
                                            :key="event.id" size="small"
                                            :type="event.type !== 'PERSONAL' ? 'success' : 'info'"
                                            :closable="event.type === 'PERSONAL'" @close="handleDeleteEvent(event)">
                                            <span class="event-tag"
                                                @click="event.type === 'PERSONAL' ? updateCalendarEventFun(event) : ''">{{
                                                    event.title }}</span>
                                        </el-tag>
                                        <span v-if="getEventsByDate(data.day).length > 4"
                                            class="text-gray-500 text-sm">...</span>
                                    </div>
                                </template>
                                <template #default>
                                    <ul>
                                        <li v-for="(event, index) in getEventsByDate(data.day)" :key="event.id">
                                            <span class="calendar-popover-text">
                                                <i
                                                    :class="['el-icon-circle-check', event.type === 'PERSONAL' ? 'bg-blue-500' : 'bg-green-500']"></i>
                                                {{ index + 1 }}. {{ event.title }}
                                                <span style="font-size: 12px;color: #999;">
                                                    ({{ event.date }})
                                                </span>
                                            </span>
                                        </li>
                                    </ul>
                                </template>
                            </el-popover>

                        </template>
                    </el-calendar>

                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import dayjs from 'dayjs';
import { ArrowLeft, ArrowRight, Plus } from '@element-plus/icons-vue';
import { getDictTypes } from "@/api/dict";
import { addCalendarEvent, updateCalendarEvent, getEventDetail, deleteEvent, getMonthCalendar } from "@/api/calendar";
import { ElMessageBox } from 'element-plus';

const calendar_event_type = ref([]);
const dialogTableVisible = ref(false);
const formRef = ref(null);
const calendarData = ref(new Date());
const form = reactive({
    title: '',
    eventDate: '',
    eventType: '',
    description: '',
    isReminder: 0
});

const rules = {
    title: [{ required: true, message: '请输入事件标题', trigger: 'blur' }],
    eventDate: [{ required: true, message: '请选择事件日期', trigger: 'change' }],
    eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }]
};

onMounted(() => {
    getDictTypesFun();
    nextTick(() => {
        getMonthCalendarFun();
    })
})

// 获取字典类型
const getDictTypesFun = () => {
    getDictTypes({ types: 'calendar_event_type' }).then(res => {
        calendar_event_type.value = res.data.calendar_event_type;
    });
}

const calendar = ref({
    selectedDay: new Date(),
});

// 选择日期
const selectDate = (val) => {
    if (!calendar.value) return;
    calendar.value.selectDate(val);
    getMonthCalendarFun();
};

// 添加日历事件
const calendarAddFun = (date) => {

    title.value = '添加';
    form.id = null;
    form.title = '';
    form.eventType = '';
    form.description = '';
    form.isReminder = 0;
    form.eventDate = date;
    dialogTableVisible.value = true;
};

// const disabledDate = (time) => {
//     return time.getTime() < Date.now() - 8.64e7;
// };

const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (title.value === '添加') {
                addCalendarEvent(form).then(res => {
                    if (res.suc) {
                        ElNotification({
                            title: '添加成功',
                            type: 'success',
                        })
                        dialogTableVisible.value = false;
                        // 刷新日历数据
                        getMonthCalendarFun();
                    } else {
                        ElNotification({
                            title: res.msg || '添加失败',
                            type: 'error',
                        })
                    }
                }).catch(err => {
                    ElNotification({
                        title: res.msg || '添加失败',
                        type: 'error',
                    })
                });
            } else {
                updateCalendarEvent(form.id, form).then(res => {
                    if (res.suc) {
                        ElNotification({
                            title: '编辑成功',
                            type: 'success',
                        })
                        dialogTableVisible.value = false;
                        // 刷新日历数据
                        getMonthCalendarFun();
                    } else {
                        ElNotification({
                            title: res.msg || '编辑失败',
                            type: 'error',
                        })
                    }
                });
            }
        }
    });
};

const monthList = ref([]);

// 获取日历数据
const getMonthCalendarFun = () => {
    monthList.value = []; // 清空之前的数据
    getMonthCalendar({
        year: new Date(calendarData.value).getFullYear(),
        month: new Date(calendarData.value).getMonth() + 1
    }).then(res => {
        if (res.suc && res.data.events) {
            monthList.value = [];
            res.data.events.forEach(item => {
                const eventTime = dayjs(item.eventTime * 1000).format('YYYY-MM-DD');
                monthList.value.push({
                    id: item.id,
                    date: eventTime,
                    title: item.title,
                    type: item.eventType,
                    tag: item.tag
                });
            });
        }
    });
};

const title = ref('添加');

// 更新事件
const updateCalendarEventFun = (event) => {
    getEventDetail(event.id).then(res => {
        title.value = '编辑';
        form.id = res.data.id;
        form.title = res.data.title;
        form.eventDate = res.data.eventDate;
        form.eventType = res.data.eventType;
        form.description = res.data.description;
        form.isReminder = res.data.isReminder;
        dialogTableVisible.value = true;
    });
}

// 获取指定日期的所有事件
const getEventsByDate = (date) => {
    return monthList.value.filter(item => item.date === date);
};

// 删除事件
const handleDeleteEvent = (event) => {
    ElMessageBox.confirm(
        '确定要删除该事件吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteEvent(event.id).then(res => {
            if (res.suc) {
                ElNotification({
                    title: '删除成功',
                    type: 'success',
                })
                getMonthCalendarFun();
            } else {
                ElNotification({
                    title: res.msg || '删除失败',
                    type: 'error',
                })
            }
        }).catch(err => {
            ElNotification({
                title: '删除失败',
                type: 'error',
            })
        });
    }).catch(() => { });
};

watch(
    () => calendarData.value,
    (newVal, oldVal) => {
        // 日历月份相同时，不刷新
        if (dayjs(oldVal).format('YYYY-MM') !== dayjs(calendarData.value).format('YYYY-MM')) {
            getMonthCalendarFun();
        }
    },
    { deep: true, immediate: false }
);

</script>

<style scoped>
.is-selected {
    color: #1989fa;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-calendar-day) {
    min-height: 160px !important;
    padding: 8px !important;
}

:deep(.el-tag__content) {
    height: 20px;
    width: calc(100% - 20px);
}

.calendar-popover-text {
    line-height: 20px;
}

.event-tag {
    /* max-width: 80px; */
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    font-size: 12px;
    line-height: 20px;
}

.el-icon-circle-check {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 3px;
    font-size: 20px;
    position: relative;
    top: -2px;
}
</style>
